#include "stack.h"

void StackInin(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = -1;
}

void StackDestroy(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->top = ps->capacity = 0;
	ps->a = NULL;
}

void StackPush(ST* ps,STDataType x)
{
	if (ps->top + 1 == ps->capacity)
	{
		int newCapacity = 
			ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = realloc(ps->a,
			sizeof(STDataType)*newCapacity);
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}
	ps->top++;
	ps->a[ps->top] = x;
}

STDataType StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	STDataType tmp = ps->a[ps->top];
	ps->top--;
	return tmp;
}

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->a[ps->top];
}

int StackSize(ST* ps)
{
	return ps->top + 1;
}

STDataType StackBottom(ST* ps)
{
	return ps->a[0];
}

bool StackEmpty(ST* ps)
{
	assert(ps);
	return ps->top == -1;
}